﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;

namespace net.xBei.Helper
{
    public static class DictHelper
    {
        public static int GetInt(this IDictionary<string, string> dict, string key, int dv)
            => dict.TryGetValue(key, out var intValue)
                ? (int.TryParse(intValue, out var outValue) ? outValue : dv)
                : dv;

        public static bool GetBoolean(this IDictionary<string, string> dict, string key, bool dv)
            => dict.TryGetValue(key, out var intValue)
                ? (bool.TryParse(intValue, out var outValue) ? outValue : dv)
                : dv;
        public static DateTime GetDateTime(this IDictionary<string, string> dict, string key, DateTime dv) 
            => dict.TryGetValue(key, out var intValue)
                ? (DateTime.TryParse(intValue, out var outValue) ? outValue : dv)
                : dv;
        
        public static Dictionary<string, string> Set(this Dictionary<string, string> dict, string key, string value) {
            dict[key] = value;
            return dict;
        }
        public static string GetVaule(this Dictionary<string, string> dict, string key)
            => GetVaule(dict, key, string.Empty);
        //public static string GetVaule(this Dictionary<string, string> dict, string key, string dv)
        //    => GetVaule(dict, key, dv);
        public static TValue GetVaule<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue dv) where TKey : notnull
            => dict == null ? dv : (dict.TryGetValue(key, out var v) ? v : dv);
        public static bool IsEquals(this Dictionary<string, string> dictA, Dictionary<string, string> dictB) {
            if (dictA == null && dictB == null) return true;
            if (dictA == null || dictB == null) return false;
            if (dictA.Count != dictB.Count) return false;
            if (dictA.Keys.All(k => dictB.Keys.Contains(k)) == false) return false;
            if (dictA.Values.All(k => dictB.Values.Contains(k)) == false) return false;
            return true;
        }

        public static Dictionary<string, string> Clone(this Dictionary<string, string> source) 
            => new Dictionary<string, string>(source);

        public static async Task<Dictionary<TKey, TValue>> ToDictionaryAsync<TSource, TKey, TValue>(this IEnumerable<TSource> source,
                                                                                                    Func<TSource, TKey> keySelector,
                                                                                                    Func<TSource, Task<TValue>> elementSelector) where TKey : notnull{
            var list = await source.SelectAsync(async i => new {
                key=keySelector(i),
                value = await elementSelector(i)
            });
            return list.ToDictionary(i => i.key, i => i.value);
        }
    }
}
